﻿using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using Configuration = NHibernate.Cfg.Configuration;

namespace Repository.NHibernate
{
    public static class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;

        private static void CreateSessionFactory()
        {
//            var connectionString = ConfigurationManager.ConnectionStrings["PostgreSQLConnectionString"].ConnectionString;
//            IPersistenceConfigurer config = PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connectionString);

            _sessionFactory = FluentNHibernate.Cfg.Fluently.Configure()
                .Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(c => c
                                                                                     .Host("localhost")
                                                                                     .Port(5432)
                                                                                     .Database("StudyControl")
                                                                                     .Username("StudyControl")
                                                                                     .Password("1111")
                              ))
                .Mappings(
                    m =>
                    m.FluentMappings.AddFromAssembly(
                        System.Reflection.Assembly.Load("Repository.NHibernate")))
//                .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();
        }

        private static void BuildSchema(Configuration config)
        {
            new SchemaExport(config).Create(true, true);
        }

        public static ISession GetSession()
        {
            if (_sessionFactory == null)
                CreateSessionFactory();

            return _sessionFactory != null ? _sessionFactory.OpenSession() : null;
        }
    }
}